# coding = utf-8

'''
可视化数据
'''

import os
import pydicom
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
from medpy.io import load, save

def get_pixels_hu(scans):
    image = np.stack([s.pixel_array for s in scans])
    # Convert to int16 (from sometimes int16),
    # should be possible as values should always be low enough (<32k)
    image = image.astype(np.int16)

    # Set outside-of-scan pixels to 1
    # The intercept is usually -1024, so air is approximately 0
    image[image == -2000] = 0

    # Convert to Hounsfield units (HU)
    intercept = scans[0].RescaleIntercept
    slope = scans[0].RescaleSlope

    if slope != 1:
        image = slope * image.astype(np.float64)
        image = image.astype(np.int16)

    image += np.int16(intercept)
    return np.array(image, dtype=np.int16)

def transform_ctdata(image, windowWidth, windowCenter, normal=False):
        """
        注意，这个函数的self.image一定得是float类型的，否则就无效！
        return: trucated image according to window center and window width
        """
        minWindow = float(windowCenter) - 0.5 * float(windowWidth)
        newimg = (image - minWindow) / float(windowWidth)
        newimg[newimg < 0] = 0
        newimg[newimg > 1] = 1
        if not normal:
            newimg = (newimg * 255).astype('uint8')
        return newimg

def visiulation():
    root = "/datasets/3Dircadb/3Dircadb1"
    patient_id = "3Dircadb1.19"
    patient_path = os.path.join(root, patient_id)
    image_path = os.path.join(patient_path, "PATIENT_DICOM")
    file_name = "image_61"
    image_file = os.path.join(image_path, file_name)
    dcm_data = pydicom.dcmread(image_file)

    image = Image.open("/home/diaozhaoshuo/log/BeliefFunctionNN/chengkung/3dircad/munet/image_tumor/case_00017/fusion/061.png")


    hu = get_pixels_hu([dcm_data]).squeeze()

    list_root = "/datasets/LITS17/volume-46.nii"
    livertumor, header = load(list_root)
    livertumor = livertumor.transpose([2,0,1])

    #plt.subplot(1, 3, 1)
    #plt.imshow(dcm_data.pixel_array, cmap="gray")
    plt.subplot(1, 3, 1)
    plt.imshow(image)
    plt.subplot(1, 3, 2)
    hu_copy = transform_ctdata(hu, 500, 150)
    plt.imshow(hu_copy, cmap="gray")

    plt.subplot(1, 3, 3)
    print(np.min(hu), np.max(hu))
    hu[hu>=250] = 250
    hu[hu<=-200] = -200
    plt.imshow(hu, cmap="gray")

    plt.show()






def read_data():
    root = "/datasets/3Dircadb/3Dircadb1"
    patient_id = "3Dircadb1.17"
    patient_path = os.path.join(root, patient_id)
    image_path = os.path.join(patient_path, "PATIENT_DICOM")
    print(len(os.listdir(image_path)))

    list_root = "/datasets/LITS17/volume-44.nii"
    livertumor, header = load(list_root)
    print(livertumor.shape)

if __name__ == '__main__':
    visiulation()